package com.example.exam.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Objects;

/**
 * @author zhang
 */
public class Md5Utils {
    private static  final Logger logger = LoggerFactory.getLogger(Md5Utils.class.getName());
    /**
     * MD5加密
     * @param s
     * @param salt
     * @return
     */
    public static byte[] md5(String s,String salt) {
        if (!salt.isEmpty()) {
            s = s + salt;
        }
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes(StandardCharsets.UTF_8));
            return algorithm.digest();
        } catch (Exception e) {
            logger.error("MD5 Error...",e);
        }
        return null;
    }
    /**
     * 将二进制的数组转换成16进制的字符串
     * @param hash
     * @return 16进制的字符串
     */
    public static String toHex(byte[] hash) {
        if (hash == null) {
            return null;
        }
        StringBuilder buf = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(String.format("%02x", b));
        }
        return buf.toString();
    }
    /**
     * 解密
     * @param s
     * @param salt
     * @return
     */
    public static String deciphering (String s,String salt) {
        return toHex(Objects.requireNonNull(md5(s,salt)));
    }
}
